package com.orange.getway.config;

import com.orange.api.constant.ConstantValue;
import com.orange.api.constant.InterceptURl;
import com.orange.api.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class MyFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
            String path = exchange.getRequest().getPath().toString();
            log.debug("进入拦截器" + path);
            // 1.判断是否需要拦截
            for (String s : InterceptURl.exInterceptUriByHead) {
                // 1.1 如果不用拦截，直接放行
                if (path.startsWith(s)){
                    return chain.filter(exchange);
                }
            }
        // 2.如果需要拦截，取出jwt，然后进行校验
        String jwt = null;
        ServerHttpRequest request = exchange.getRequest();
        List<String> lists = request.getHeaders().get(ConstantValue.TokenKey);
        if (lists != null && !lists.isEmpty()){
            // 这里我们可以确认authorization只有一个，所有直接使用他
            jwt = lists.get(0);
        }
        try{
            String s = JwtUtil.parseJwt(jwt);
            // 2.1 校验成功，直接放行
            return chain.filter(exchange);
            // 否则抛出异常
        }catch (Exception e){
            log.error("jwt验证出现错误:" + e.getMessage());
        }

        return chain.filter(exchange);

    }

    @Override
    public int getOrder() {
        return 0;
    }
}